﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace SXFramWork.Core
{
    public class LogHandler : ILogHandler
    {
        private readonly ILoginInfo _loginInfo;
        public LogHandler(ILoginInfo loginInfo)
        {
            _loginInfo = loginInfo;
        }
        public async Task LogAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {

            var sw = new Stopwatch();
            sw.Start();
            var actionExecutedContext = await next();
            sw.Stop();

            var title = "";
            object[] attributesmenu = context.ActionDescriptor.EndpointMetadata.Where(m => m.GetType() == typeof(MenuAttribute)).ToArray();

            object[] attributespower = context.ActionDescriptor.EndpointMetadata.Where(m => m.GetType() == typeof(PowerAttribute)).ToArray();

            object[] attributesapipower = context.ActionDescriptor.EndpointMetadata.Where(m => m.GetType() == typeof(ApiPowerAttribute)).ToArray();

            if (attributesmenu != null && attributesmenu.Length == 1)
            {
                MenuAttribute _atmenu = attributesmenu[0] as MenuAttribute;
                title = _atmenu.Title;
            }
            if (attributespower != null && attributespower.Length == 1)
            {
                PowerAttribute _atpower = attributespower[0] as PowerAttribute;
                title = _atpower.Title;
            }
            if (attributesapipower != null && attributesapipower.Length == 1)
            {
                ApiPowerAttribute _atapipower = attributesapipower[0] as ApiPowerAttribute;
                title = _atapipower.Title;
            }
            try
            {

                var ApiMethod = context.HttpContext.Request.Method.ToLower();
                var ApiPath = context.ActionDescriptor.AttributeRouteInfo.Template.ToLower();
                var elapsedMilliseconds = sw.ElapsedMilliseconds;
                var Status = 0;
                var Msg = "";
                if (actionExecutedContext.Result is ObjectResult result && result.Value is IApiResult res)
                {
                    Status = res.Success==true?1:0;
                    Msg = res.Msg;
                }
                //通过NLog将操作日志写入到数据库
                Loghelper.Default.writedblog(_loginInfo.UserName,Msg,title, 0, Status, elapsedMilliseconds);
            }
            catch (Exception ex)
            {
                Loghelper.Default.writelog(ex,"操作日志记录发生异常："+ex.Message);
            }
        }
    }
}
